<template>
    <el-dialog title="新增轮播图" width="450" @close="closeDialog">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="formLabelWidth">
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input v-model="form.sort" autocomplete="off" />
            </el-form-item>
            <!-- 图片 -->
            <el-form-item label="图片" prop="image">
                <el-upload class="avatar-uploader" action="http://localhost:7070/api/admin/common/upload" method="post"
                    :headers="headers" name="file" list-type="picture" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="form.image" :src="form.image" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" color="#000" @click="submitForm">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useUserStore } from '@/stores/user.js'
import { ElMessage } from 'element-plus';
import { addBanner, getBannersById, updateBanner } from '@/api/banners.js'


const userStore = useUserStore()
const headers = ref({ 'token': userStore.viewToken })
const emit = defineEmits(['update:modelValue', 'refresh', 'update:transferId']);
// 定义接收的 props
const props = defineProps(['transferId']);
// 监听 transferId 的变化
watch(() => props.transferId, (newValue) => {
    // localtransferId.value = newValue;
    if (newValue) {
        getBannersById(newValue).then(res => {
            form.value = { ...form.value, ...res.data };
        }).catch(err => {
            console.log(err);
        });
    }
});
const formRef = ref(null)
const form = ref({
    id: '',
    name: '',
    sort: '',
    image: ''
});
// 非空校验规则
const rules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
    image: [{ required: true, message: '请上传图片', trigger: 'blur' }]
}

const submitForm = async () => {
    await formRef.value.validate(async (valid) => {
        if (valid) {
            // 判断是新增还是修改
            if (props.transferId) {
                // 修改部门
                const res = await updateBanner(form.value);
                if (res.code === 1) {
                    ElMessage.success('修改成功');
                    emit('refresh');
                } else {
                    ElMessage.error('修改失败');
                }
            } else {
                // 新增部门
                const res = await addBanner(form.value);
                if (res.code === 1) {
                    ElMessage.success('新增成功');
                    emit('refresh');
                } else {
                    ElMessage.error('新增失败');
                }
            }
            closeDialog();
        }
    })
};

const closeDialog = async () => {
    // console.log('关闭弹窗');
    formRef.value.resetFields(); // 重置表单
    emit('update:modelValue', false); // 确保更新为 false
    emit('update:transferId', null);
};
const handleAvatarSuccess = (response, uploadFile) => {
    // console.log(response);
    form.value.image = response.data; // 同步到form.image
    ElMessage.success('上传成功');
}

const beforeAvatarUpload = (rawFile) => {
    // console.log(rawFile);
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif' && rawFile.type !== 'image/webp') {
        ElMessage.error('必须为图片格式！')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像图片大小不能超过 2MB！')
        return false
    }
    return true
}




</script>

<style lang="scss" scoped>
.avatar-uploader {
    width: 178px;
    height: 178px;
    display: block;
    border: 2px dashed #d9d9d9;

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;

    }
}
</style>
